var jsonFormData = {
    search_value: "",   
    "column-sort": "",
    "column-sort-type": "", 
}
var columnSort = [];
$(document).ready(function(){
	var pathname = window.location.pathname;
	FormCategory.init();
	

	$("body").on("keyup","#txtSearchFormCategoryDatatable",function(e){
        $("#loadFormCategory").dataTable().fnDestroy();
        jsonFormData['search_value'] = $(this).val();
        FormCategory.triggerDataTable();
    })

	$("body").on("click",".addCategoryModal",function(){
    	var json = {};
    	json['title'] = "Add Form Category";
    	json['value'] = '';
    	json['button'] = '<input type="button" class="btn-blueBtn addCategory fl-margin-right" value="Save">';
    	FormCategory.categoryModal(json);
    })
    $("body").on("click",".updateformCategory",function(){
    	var json = {};
    	var category_id = $(this).attr("data-id");
    	json['title'] = "Edit Form Category";
    	json['value'] = $(this).attr("data-name");
    	json['users'] = $(".users_"+category_id).text();
    	json['image'] = $(".image_"+category_id).text();
    	json['button'] = '<input type="button" data-id="'+ category_id +'" class="btn-blueBtn editCategory fl-margin-right" value="Save">';
    	FormCategory.categoryModal(json);
    })
    $("body").on("click","#loadFormCategory th",function(){
        var cursor = $(this).css("cursor");
        jsonFormData['column-sort'] = $(this).attr("field_name");
        if($(this).attr("field_name")=="" || $(this).attr("field_name")==undefined){
            return;
        }
        var indexcolumnSort = columnSort.indexOf($(this).attr("field_name"));

        $(this).closest("#loadFormCategory").find(".sortable-image").html("");
        if(indexcolumnSort==-1){
            columnSort.push($(this).attr("field_name"))
            $(this).find(".sortable-image").html("<i class='fa fa-sort-asc'></i>")
            jsonFormData['column-sort-type'] = "ASC";
        }else{
            columnSort.splice(indexcolumnSort,1);
            $(this).find(".sortable-image").html("<i class='fa fa-sort-desc'></i>")
            jsonFormData['column-sort-type'] = "DESC";
        }
        
        $("#loadFormCategory").dataTable().fnDestroy();
        FormCategory.triggerDataTable();
    })
})
FormCategory = {
	init : function(){
		this.deleteformCategory();
		this.addCategory();
		this.editCategory();
		this.triggerDataTable();
	},
	triggerDataTable : function(){
		if (pathname=="/form_category") {
		    this.load();
		    
		}else if(pathname=="/user_view/form_category"){
			FormCategory.defaultData();
		}
	},
	load : function(){
		//code here
		var oTable = $('#loadFormCategory').dataTable( {
                     "bProcessing": true,
                     "bRetrieve": true,
                     "aaSorting" : [[2,"desc"]],
                     //"bPaginate": true,//"sEcho":3,//"iTotalDisplayRecords":10,//"iTotalRecords":"10",
                     //"iTotalDisplayRecords":"10",//"bServerSide": true,
                     "sAjaxSource": "/ajax/form_category",
                     "sPaginationType": "full_numbers",
                     "sAjaxDataProp": "company_user",
                     "aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                     "aoColumns": [
                         { "mData": "title" },
                         { "mData": "actions" }
                     ],
                     "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                         $("#example_length > label > select").addClass("selectlength");
                     },
                     "aoColumnDefs": [ {
                         "bSortable": true, "aTargets": [ 0,1 ]
                         },{
                             "bSortable": false, "aTargets": [ "_all" ]
                         }/*, {
                             "bSearchable": true, "aTargets": [ 0 ]
                         }, {
                             "bSearchable": false, "aTargets": [ "_all" ]
                     }*/
                     ],
                     "fnServerData": function (sSource, aoData, fnCallback) {
                         $.ajax({
                             type: "POST",
                             cache: false,
                             dataType: 'json',
                             url: sSource,
                             data: {action:"loadFormCategory"},
                             success: function (json) {
                                 // Retrieve data
                                 //console.log(json)
                                 fnCallback(json);
                             }
                         });
                     }
                 });
                return oTable;
	},
	deleteformCategory : function(){
		//code here
		var self = this;
		$("body").on("click",".deleteformCategory",function(){
			var id = $(this).attr("data-id");
			var newConfirm = new jConfirm("Warning,<br /> All form that has this category will automatically move to '<b>other forms</b>' section", 'Confirmation Dialog','', '', '', function(r){
			 	if(r==true){
			 		//get forms
			 		ui.block();
			 		$.post("/ajax/form_category",
			 		{
			 			action:"deleteformCategory",
			 			id:id
			 		},function(data){
			 			// console.log(data)
			 			data = JSON.parse(data);
			 			var form_json = "";
			 			var formToUpdate = [];
			 			for(var i in data){
			 				form_json = JSON.parse(data[i]['form_json']);
			 				form_json['form_json']['form_category'] = 0;
                        	form_json['categoryName'] = 0;
			 				formToUpdate.push({
			 					"id":data[i]['id'],
			 					"form_json":JSON.stringify(form_json)
			 				})
			 			}
			 			//update forms
			 			$.post("/ajax/form_category",{formToUpdate:formToUpdate,action:"updateForms",id:id},function(data2){
			 				// console.log(data2);
			 				$('#loadFormCategory').dataTable().fnDestroy();
							FormCategory.triggerDataTable();
							ui.unblock();
			 			})
			 		// 	$('#loadFormCategory').dataTable().fnDestroy();
						// self.load();
			 		})

				 	// $.ajax({
	     //                 type: "POST",
	     //                 cache: false,
	     //                 dataType: 'json',
	     //                 url: "/ajax/form_category",
	     //                 data: {action:"deleteformCategory"},
	     //                 success: function (jsondata) {
	     //                     // Retrieve data
	     //                     //console.log(json)
	     //                     // fnCallback(json);
	     //                     console.log(jsondata)
	     //                 }
	     //             });
			 	}
			 })
		newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});
		});
	},

	categoryModal : function(json){
		var self = this;
		var departments = $(".departments").text();
		var positions = $(".positions").text();
		var users = $(".users").text();
		var departments_arr;var positions_arr;var users_arr;
		var formPrivacy = json['users'];
		var image = json['image'];
		if(formPrivacy){
			formPrivacy = JSON.parse(formPrivacy);
			departments_arr = formPrivacy['departments'];
			positions_arr = formPrivacy['positions'];
			users_arr = formPrivacy['users'];
		}
		// $("body").on("click",".addCategoryModal",function(){
			var ret = '<h3><i class="icon-print"></i> '+ json.title +'</h3>';
                ret += '<div class="hr"></div>';
                ret += '</div>';
                 ret += '<div id="accordion-container">';
                ret += '    <ul>';
                ret += '        <li><a href="#tabs-1">Primary Settings</a></li>';
                ret += '        <li><a href="#tabs-2">Logo</a></li>';
                ret += '    </ul>';
                ret += '<div id="comment-container" style="position: relative; margin: 0px auto; padding: 0px; width: 100%; overflow: hidden;height: 300px" class="ps-container">'
                ret += '<div class="content-dialog sub-container-comment requestComment" style="width: 100%;">';
               
                ret += '    <div id="tabs-1">';
	                ret += '    <div class="pull-left" style="width: 100%">';
	                ret += '    	<div class="fields_below">';
	                ret += '    		<div class="label_below2">Category Name: <font color="red">*</font></div>';
	                ret += '    	<div class="input_position_below" style="width:50%; margin-bottom:10px;">';
	                ret += '    		<input type="text" name="" data-type="textbox" class="form-text category_name" value="'+ json.value +'"></div>';
	               	ret += '     	</div>';
	                ret += '    </div>';
	                ret += '<div class="fp-container" style="height: 265px;width:98%">';
					    ret += '<div class="input_position" style="width:100%">';
						    ret += '<div style="margin-top: 10px;">';
							ret += '<label><input type="checkbox" class="fp-allUsers css-checkbox" value="All Users" id="fp-allUsers7"/><label for="fp-allUsers7" class="css-label"></label> All Users</label> <br />';
							ret += '<div style="margin-left: 20px;">';
								ret += '<div class="container-formUser">';
									ret += '<div class="formUser" rel="getDepartmentFF" ><label class="fa fa-minus"></label> <label class="font-bold">Department</label></div>';
									ret += '<div class="getDepartmentFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
									
									var ctr_dept = 0;
									if(departments){
										departments = JSON.parse(departments);
										$.each(departments,function(key, val){
											ret += '<div style="width:32%;float:left;margin-bottom:2px"> ';
											//setCheckedArray(value, arr)
												ret += '<label class="tip" title="'+ val.department +'"><input type="checkbox" class="fp-user departments css-checkbox" '+ RequestPivacy.setCheckedArray(val.id, departments_arr) +' value="'+ val.id +'" id="fp-user-dept_'+ val.id +'"/><label for="fp-user-dept_'+ val.id +'" class="css-label"></label> <span class="limit-text-ws">'+ val.department +'</span></label>';
											ret += '</div>';
											ctr_dept++
										})
									}
									if(ctr_dept==0){
										ret += '<span style="color:red">No Department</span>';
									}
									ret += '</div>';
								ret += '</div>';
								// for position
								ret += '<div class="container-formUser">';
									ret += '<div class="formUser" rel="getPositionFF" ><label class="fa fa-minus"></label> <label class="font-bold">Position</label></div>';
									ret += '<div class="getPositionFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
										
										var ctr_pos = 0;
										if(positions){
											positions = JSON.parse(positions);
											$.each(positions,function(key, val){
												if(val.position !=""){
													ret += '<div style="width:32%;float:left;margin-bottom:2px"> ';
														ret += '<label class="tip" title="'+ val.position +'"><input type="checkbox" class="fp-user positions css-checkbox" '+ RequestPivacy.setCheckedArray(val.position, positions_arr) +' value="'+ val.position +'" id="fp-user_positions_'+ val.position +'"/><label for="fp-user_positions_'+ val.position +'" class="css-label"></label> <span class="limit-text-ws">'+ val.position +'</span></label>';
													ret += '</div>';
													ctr_pos++;
												}
											})
											
										}
									if(ctr_pos==0){
										ret += '<span style="color:red">No Positions</span>';
									}	
									ret += '</div>';
								ret += '</div>';
								//for users
								ret += '<div class="container-formUser">';
								ret += '<div class="formUser" rel="getUsersFF" ><label class="fa fa-minus"></label> <label class="font-bold">Users</label></div>';
									ret += '<div class="getUsersFF" style="display:inline-block;width:100%;margin-left:10px;margin-top:5px;">';
										
										var ctr_usr = 0
										if(users){
											users = JSON.parse(users);
											$.each(users,function(key, val){
												ret += '<div style="width:32%;float:left;margin-bottom:2px;"> ';
													ret += '<label class="tip" title="'+ val.first_name +' '+ val.last_name +'"><input type="checkbox" class="fp-user users css-checkbox" '+ RequestPivacy.setCheckedArray(val.id, users_arr) +' value="'+ val.id +'" id="fp-user users_'+ val.id +'"/><label for="fp-user users_'+ val.id +'" class="css-label"></label> <span class="limit-text-ws">'+ val.first_name +' '+ val.last_name +'</span></label>';
												ret += '</div>';
												ctr_usr++
											})
											
										}
										if(ctr_usr==0){
											ret += '<span style="color:red">No Users</span>';
										}	
								ret += '</div>';
								ret += '</div>';
							ret += '</div>';
						ret += '</div>';
					ret += '</div>';
				ret += '</div>';
				ret += '</div>';
				ret += '    <div id="tabs-2">';
					for(var i in categoryLogo){
						ret += "<div style='float:left;width:27%;margin-right:30px;'><label><input type='radio' class='category-logo css-checkbox' name='category-logo' value='"+ categoryLogo[i]['id'] +"' id='categoryLogo_"+ categoryLogo[i]['id'] +"'><label for='categoryLogo_"+ categoryLogo[i]['id'] +"' class='css-label'></label> <div style='background-color:"+ categoryLogo[i]['bg-color'] +";width:100%;border-radius: 100%;'><img style='height:100%;width:100%' src='/images/icon/app-logo/"+ categoryLogo[i]['imgpath'] +"' /></div><label></div>";
					}
				ret += '	</div>';
				ret += '</div>';
                ret += '</div>';
                ret += '</div>';
                //ret += '<div class="fields" style="border-top:1px solid #ddd;">';
                ret += '<div class="label_basic"></div>';
                ret += '<div class="input_position" style="margin-top:5px;text-align:right;">';
                ret += json.button;
                ret += ' <input type="button" class="btn-basicBtn" id="popup_cancel" value="Close">';
                ret += '</div>';
                ret += '</div>';
               var newDialog = new jDialog(ret, "", "700", "", "25", function() {

                });
                newDialog.themeDialog("modal2");
                limitText(".limit-text-ws",20);
                RequestPivacy.setCheckAllChecked(".fp-user");
                $('#comment-container').perfectScrollbar();

                $( "#accordion-container" ).tabs({
		            activate : function(){
		                $('#comment-container').perfectScrollbar("update");
		            }
		        })
                RequestPivacy.bindOnClickCheckBox();
                if(image){
                	$(".category-logo[value='"+ image +"']").attr("checked","checked");
                }
		// })
	},
	addCategory : function(){
		var self = this;
		$("body").on("click",".addCategory",function(){
			var category_name = $(".category_name").val();
			var departments = new Array();
			var positions = new Array();
			var users = new Array();
			var json_privacy = {};
			var logo = $(".category-logo:checked").val()
			if(category_name==""){
				showNotification({
	                 message: "Please fill out required fields",
	                 type: "error",
	                 autoClose: true,
	                 duration: 3
                });
				return;
			}

			
			//for deoartments
			$(".departments").each(function(){
				if($(this).prop("checked")){
					departments.push($(this).val());
				}
			})
			//for positions
			$(".positions").each(function(){
				if($(this).prop("checked")){
					positions.push($(this).val());
				}
			})
			//for users
			$(".users").each(function(){
				if($(this).prop("checked")){
					users.push($(this).val());
				}
			})
			json_privacy['departments'] = departments;
			json_privacy['positions'] = positions;
			json_privacy['users'] = users;
			json_privacy = JSON.stringify(json_privacy);
			$.post("/ajax/form_category",
	 		{
	 			action:"addCategory",
	 			category_name:category_name,
	 			users:json_privacy,
	 			logo:logo
	 		},function(data){
	 			$('#loadFormCategory').dataTable().fnDestroy();
				self.triggerDataTable();
	 			showNotification({
	                 message: "Form Category Added",
	                 type: "success",
	                 autoClose: true,
	                 duration: 3
                });
	 			$("#popup_cancel").click();
	 		})
		})
	},
	editCategory : function(){
		var self = this;
		$("body").on("click",".editCategory",function(){
			var category_name = $(".category_name").val();
			var category_id = $(this).attr("data-id");
			var logo = $(".category-logo:checked").val()
			if(category_name==""){
				showNotification({
	                 message: "Please fill out required fields",
	                 type: "error",
	                 autoClose: true,
	                 duration: 3
                });
				return;
			}
			var departments = new Array();
			var positions = new Array();
			var users = new Array();
			var json_privacy = {};

			if(category_name==""){
				showNotification({
	                 message: "Please fill out required fields",
	                 type: "error",
	                 autoClose: true,
	                 duration: 3
                });
				return;
			}
			//for deoartments
			$(".departments").each(function(){
				if($(this).prop("checked")){
					departments.push($(this).val());
				}
			})
			//for positions
			$(".positions").each(function(){
				if($(this).prop("checked")){
					positions.push($(this).val());
				}
			})
			//for users
			$(".users").each(function(){
				if($(this).prop("checked")){
					users.push($(this).val());
				}
			})
			json_privacy['departments'] = departments;
			json_privacy['positions'] = positions;
			json_privacy['users'] = users;
			json_privacy = JSON.stringify(json_privacy);
			$.post("/ajax/form_category",
	 		{
	 			action:"editCategory",
	 			category_name:category_name,
	 			users:json_privacy,
	 			category_id:category_id,
	 			logo:logo
	 		},function(data){
	 			$('#loadFormCategory').dataTable().fnDestroy();
				self.triggerDataTable();
	 			showNotification({
	                 message: "Form Category Updated",
	                 type: "success",
	                 autoClose: true,
	                 duration: 3
                });
	 			$("#popup_cancel").click();
	 		})
		})
	},
	"defaultData" : function(){
        var oTable = $('#loadFormCategory').dataTable( {
            "sDom": 'Rlfrtip',
            // "sScrollY": "400px",
            "oLanguage": {
                "sProcessing": '<div class="spinner load_m"> '+
                       '<div class="bar1"></div> '+
                       '<div class="bar2"></div> '+
                       '<div class="bar3"></div> '+
                       '<div class="bar4"></div> '+
                       '<div class="bar5"></div> '+
                       '<div class="bar6"></div> '+
                      '<div class="bar7"></div> '+
                      '<div class="bar8"></div> '+
                      '<div class="bar9"></div> '+
                      '<div class="bar10"></div> '+
                 '</div>'
            },
            "oColReorder": false,
            "bLengthChange": false,
            "bFilter": false,
            "bProcessing": true,
            "bServerSide": true,
            "sPaginationType": "full_numbers",
            "bSort": false,
            "sAjaxSource": "/ajax/form_category",
            "fnServerData": function(sSource, aoData, fnCallback) {
                aoData.push({"name": "search_value", "value": jsonFormData['search_value']});
                aoData.push({"name": "action", "value": "loadFormCategoryDatatable"});
                aoData.push({"name": "column-sort", "value": jsonFormData['column-sort']});
                aoData.push({"name": "column-sort-type", "value": jsonFormData['column-sort-type']});
                
                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": function(data) {
                        console.log(data)
                        // return;
                        fnCallback(data);
                    }
                });
            },
            "fnInitComplete": function(oSettings, json) {
                // 
            }
        });
        return oTable;
    }
}